package mysql

import (
	"errors"
	"fmt"
	"gitee.com/captials-team/ubdframe/src/domain/configstc"
	"gitee.com/captials-team/ubdframe/src/domain/interfaces"
	"gitee.com/captials-team/ubdframe/src/domain/models"
	mysqlClients "gitee.com/captials-team/ubdframe/src/infrastructure/clients/mysql"
	"gorm.io/gorm"
)

func NewUserAccountDao(conf configstc.DBConfig) *UserAccountDao {
	return &UserAccountDao{
		db:   mysqlClients.NewGormDB(conf),
		conf: conf,
	}
}

type UserAccountDao struct {
	db   *gorm.DB
	conf configstc.DBConfig
}

func (dao *UserAccountDao) Migrate() (int64, error) {
	return 1, dao.db.AutoMigrate(new(models.UserAccount))
}

func (dao *UserAccountDao) QueryByAccount(account string) (*models.UserAccount, error) {
	var info models.UserAccount
	ret := dao.db.Model(&info).First(&info, "account = ?", account)
	if errors.Is(ret.Error, gorm.ErrRecordNotFound) {
		return nil, nil
	}
	if ret.Error != nil {
		return nil, ret.Error
	}
	return &info, nil
}

func (dao *UserAccountDao) Add(add *models.UserAccount) (int64, error) {
	if add.Id > 0 {
		return 0, fmt.Errorf("not support update")
	}
	ret := dao.db.Model(add).Create(add)
	if ret.Error != nil {
		return 0, ret.Error
	}
	if ret.RowsAffected == 0 {
		return 0, fmt.Errorf("add fail")
	}

	return add.Id, nil
}

func (dao *UserAccountDao) Delete(id int64) (int64, error) {
	ret := dao.db.Where("id=?", id).Delete(&models.UserAccount{})
	if ret.Error != nil {
		return 0, ret.Error
	}
	if ret.RowsAffected == 0 {
		return 0, fmt.Errorf("no delete")
	}
	return ret.RowsAffected, nil
}

func (dao *UserAccountDao) Use(db *gorm.DB) interfaces.ItfUserAccount {
	return &UserAccountDao{db: db}
}

func (dao *UserAccountDao) DB() *gorm.DB {
	return dao.db
}
